package com.bangyu.monitor.core.util;

import com.bangyu.monitor.core.common.constant.Const;
import com.bangyu.monitor.modular.system.entity.OriginalData;
import com.bangyu.monitor.modular.system.entity.Payload;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;

import java.util.List;
import java.util.Map;

/**
 * @Auther: zhangxue
 * @Date: 19/6/25 23:48
 * @Description:负责原始数据入库和数据文件落地
 */
@Slf4j
public class InfluxOriginalDbUtil {

    public static void insertOriginalData(List<OriginalData> datas){
        if(CollectionUtils.isNotEmpty(datas)){
            BatchPoints batchPoints = InfluxDbUtil.createBatchPoints(Const.INFLUX_DB_MONITOR,Const.RETENTION_ORIGINAL_DATA);
            for(OriginalData data:datas){
                Point point = originalData2Point(data);
                batchPoints.point(point);
            }
            InfluxDbUtil.batchInsert(batchPoints);
            log.info(getSql(datas));
        }
    }

    private static String getSql(List<OriginalData> datas){
        String sql = "";
        if(CollectionUtils.isNotEmpty(datas)){
            StringBuilder sb = new StringBuilder();
            for(OriginalData data:datas){
                sb.append(String.format("%d,%s,%f,%f,%f,%f,%f,%f,%f,%f\n",
                        data.getReceiveTime(),data.getDeviceNo(),data.getV0(),
                        data.getV1(),data.getV2(),data.getV3(),data.getV4(),data.getV5(),data.getV6(),data.getV7()));
            }
            sql = sb.toString();
        }
        return sql;
    }

    private static Point originalData2Point(OriginalData data){

        Map<String, String> tags = Maps.newHashMap();
        Map<String, Object> fields = Maps.newHashMap();

        tags.put("device_no",data.getDeviceNo());

        fields.put("td1",data.getV0());
        fields.put("td2",data.getV1());
        fields.put("td3",data.getV2());
        fields.put("td4",data.getV3());
        fields.put("td5",data.getV4());
        fields.put("td6",data.getV5());
        fields.put("td7",data.getV6());
        fields.put("td8",data.getV7());
        return InfluxDbUtil.createPoint(Const.MEASUREMENT_ORIGINAL_DATA,tags,fields,data.getReceiveTime());
    }








}
